package com.zlkj.pro.modular.business.service.impl;

import cn.stylefeng.roses.kernel.auth.api.context.LoginContext;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.system.api.pojo.user.SysUserDTO;
import cn.stylefeng.roses.kernel.system.api.pojo.user.request.SysUserRequest;
import cn.stylefeng.roses.kernel.system.modular.user.entity.SysUser;
import cn.stylefeng.roses.kernel.system.modular.user.mapper.SysUserMapper;
import cn.stylefeng.roses.kernel.system.modular.user.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlkj.pro.core.consts.ProjectConstants;
import com.zlkj.pro.core.exception.BusinessException;
import com.zlkj.pro.core.util.ConvertUtil;
import com.zlkj.pro.modular.admin.entity.User;
import com.zlkj.pro.modular.admin.mapper.UserMapper;
import com.zlkj.pro.modular.admin.model.dto.UserDTO;
import com.zlkj.pro.modular.admin.model.vo.UserVO;
import com.zlkj.pro.modular.admin.service.UsersService;
import com.zlkj.pro.modular.business.entity.AgentEntity;
import com.zlkj.pro.modular.business.mapper.AgentMapper;
import com.zlkj.pro.modular.business.model.dto.AgentDTO;
import com.zlkj.pro.modular.business.model.dto.CustomerDTO;
import com.zlkj.pro.modular.business.model.vo.AgentVO;
import com.zlkj.pro.modular.business.service.AgentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.zlkj.pro.core.exception.enums.BusinessExceptionEnum.BUSINESS_EXCEPTION;

/**
 * @author liyang
 * @date 2024/4/6
 * @time 14:34
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class AgentServiceImpl extends ServiceImpl<AgentMapper, AgentEntity> implements AgentService {

    @Autowired
    private AgentMapper agentMapper;

    @Autowired
    private UsersService usersService;

    @Autowired
    private Environment env;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult<AgentVO> findPage(AgentDTO dto) {
        Integer pageNo = dto.getPageNo();
        Integer pageSize = dto.getPageSize();
        dto.setUserId(LoginContext.me().getLoginUser().getUserId());
        extracted(dto);
        List<AgentVO> list = agentMapper.findPage(dto);
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(vo -> {
                vo.setLogoUrl(env.getProperty("file-path") + vo.getLogoFileId());
            });
        }
        Long total = agentMapper.findPageCount(dto);
        return PageResultFactory.createPageResult(list, total, pageSize, pageNo);
    }

    private void extracted(AgentDTO dto) {
        SysUserRequest sysUserRequest = new SysUserRequest();
        sysUserRequest.setUserId(dto.getUserId());
        SysUserDTO currentUser = sysUserService.detail(sysUserRequest);
        Long roleId = currentUser.getGrantRoleIdList().get(0);
        if (ProjectConstants.ROLE_ID_BMSH_MANAGER.equals(roleId)) {
            dto.setRoleId(1);
        } else if (ProjectConstants.ROLE_ID_BMSH_YG.equals(roleId)) {
            dto.setRoleId(2);
        } else if (ProjectConstants.ROLE_ID_AGENT_MANAGER.equals(roleId)) {
            dto.setRoleId(3);
        } else if (ProjectConstants.ROLE_ID_JL.equals(roleId)) {
            dto.setRoleId(4);
        } else if (ProjectConstants.ROLE_ID_YG.equals(roleId)) {
            dto.setRoleId(5);
        }
    }

    @Override
    public List<AgentVO> findList(AgentDTO dto) {
        // 获取用户代理商 ID
        User userVo = userMapper.selectById(LoginContext.me().getLoginUser().getUserId());
        // 如果当前用户有所属代理商 那么下拉列表也只查看自己的所在的代理商
        LambdaQueryWrapper<AgentEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AgentEntity::getStatusFlag, 1);
        if (userVo.getAgentId() != null) {
            queryWrapper.eq(AgentEntity::getId, userVo.getAgentId());
        }
        // 如果当前用户有所属地域 那只能查看自己所在地域的代理商
        if (StringUtils.isNotBlank(userVo.getRegion())) {
            queryWrapper.in(AgentEntity::getRegion, Arrays.asList(userVo.getRegion().split(",")));
        }
        queryWrapper.orderByDesc(AgentEntity::getCreateTime);
        List<AgentEntity> productInfoEntityList = super.list(queryWrapper);
        return ConvertUtil.turn(productInfoEntityList, AgentVO.class);
    }

    @Override
    public AgentVO findDetail(AgentDTO dto) {
        Long id = dto.getId();
        LambdaQueryWrapper<AgentEntity> productInfoEntityLambdaQueryWrapper = Wrappers.lambdaQuery();
        productInfoEntityLambdaQueryWrapper.eq(AgentEntity::getId, id);
        AgentEntity productInfoEntity = super.getOne(productInfoEntityLambdaQueryWrapper, Boolean.FALSE);
        return ConvertUtil.turn(productInfoEntity, AgentVO.class);
    }

    @Override
    public boolean add(AgentDTO dto) {
        if (dto.getLogoFileId() == null) {
            dto.setLogoFileId(1791069323788275714L);// 默认代理商logo
        }
        if (dto.getExpirationDateStart() == null) {
            throw new BusinessException(BUSINESS_EXCEPTION, "请填写代理商有效期");
        }
        if (dto.getExpirationDateEnd() == null) {
            throw new BusinessException(BUSINESS_EXCEPTION, "请填写代理商有效期");
        }
        if (StringUtils.isBlank(dto.getArea())) {
            throw new BusinessException(BUSINESS_EXCEPTION, "请选择负责区域");
        }
        AgentEntity productInfoEntity = ConvertUtil.turn(dto, AgentEntity.class);
        productInfoEntity.setUpdateTime(new Date());
        return super.save(productInfoEntity);
    }

    @Override
    public boolean edit(AgentDTO dto) {
        AgentEntity productInfoEntity = ConvertUtil.turn(dto, AgentEntity.class);
        super.updateById(productInfoEntity);

        // 禁用代理商下所有账号
        if (productInfoEntity.getStatusFlag() == 2) {
            // 按agentId 更新statusFlag
            User entity = new User();
            entity.setStatusFlag(2);
            LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(User::getAgentId, dto.getId());
            usersService.update(entity, queryWrapper);
        }
        return super.updateById(productInfoEntity);
    }

    @Override
    public boolean delete(AgentDTO dto) {
        return super.removeById(dto);
    }

    @Override
    public boolean batchDelete(List<Long> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            return super.removeByIds(ids);
        }
        return true;
    }

}
